import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';

///**
///* Description: 下拉显示列表的小部件
///*/
typedef OnChanged<T> = void Function(String value);

class DropDownWidget extends StatefulWidget {
  final double height;

  final double fontSize;

  final List<BaseSelectModel> items;

  final OnChanged onChanged;

  final bool isExpanded;

  ///需要显示的item
  final int itemIndex;

  ///是否显示边框
  final bool showBorder;

  ///文本是否居中
  final bool textIsCentered;

  const DropDownWidget({Key key, @required this.items, this.onChanged, this.height, this.fontSize, this.isExpanded = false, this.itemIndex = 0, this.showBorder = true, this.textIsCentered = false}) : super(key: key);

  @override
  _DropDownWidgetState createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget> {
  String _selected;

  @override
  void initState() {
    this._selected = widget.items.length > 0 ? widget.items[0].key : null;
    if (widget.itemIndex <= widget.items.length && widget.itemIndex != -1) {
      this._selected = widget.items[widget.itemIndex].key;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return _buildDropDownContainer(
      child: DropdownButton(
        isDense: true,
        elevation: 0,
        iconSize: 20,
        isExpanded: widget.isExpanded,
        value: _selected,
        style: Theme.of(context).textTheme.bodyText2,
        items: widget.items.map((select) => _buildDropdownButtonItem(select)).toList(),
        onChanged: _onChanged,
        underline: Container(),
      ),
    );
  }

  Widget _buildDropDownContainer({Widget child}) {
    return Container(
      height: widget.height == null ? 20.0 : widget.height,
      padding: const EdgeInsets.only(left: 4.0),
      decoration: new BoxDecoration(border: widget.showBorder ? Border.all(color: Theme.of(context).textTheme.bodyText2.color) : Border.all(color: Colors.white), borderRadius: BorderRadius.circular(4.0)),
      child: child,
    );
  }

  void _onChanged(String value) {
    setState(() {
      _selected = value;
    });
    widget.onChanged(value);
  }

  DropdownMenuItem<String> _buildDropdownButtonItem(BaseSelectModel select) {
    return DropdownMenuItem<String>(child: widget.textIsCentered ? Container(alignment: Alignment.center, child: Text(select.value, style: TextStyle(fontSize: widget.fontSize == null ? 8 : widget.fontSize))) : Text(select.value, style: TextStyle(fontSize: widget.fontSize == null ? 8 : widget.fontSize)), value: select.key);
  }
}
